import { Component, SpriteFrame, Texture2D, Node, resources, Prefab, instantiate, Sprite, assetManager, ImageAsset, RigidBody, RigidBody2D, Vec2 } from 'cc';
/**
 * 游戏辅助类
 */
export class GameHelper {
    parent: Node;
    maps: any = {};
    limit: number = 30;
    constructor(node: Node) {
        this.parent = node;
    }
    /**
     * 执行弹幕命令
     * @param data 命令数据
     */
    coomand(data: any) {
        this.addUser(data.uid, data.name, data.head);
    }

    addUser(uid: string, name: string, img: string) {
        if (this.maps[uid]) {
            return;
        }
        if (this.limit <= 0)
            return;
        this.limit--;
        resources.load("prefabs/role", Prefab, (err, prefab) => {
            let newNode = instantiate(prefab);
            let childNode: any = newNode.children[0].children[1].children[0];
            var rigid = newNode.children[0].getComponent(RigidBody2D);

            rigid.linearVelocity = new Vec2(this.random(-5, 5), this.random(-5, 5));
            assetManager.loadRemote<ImageAsset>(img, (err, imageAsset) => {
                const sprite = childNode.getComponent(Sprite);
                sprite.spriteFrame = SpriteFrame.createWithImage(imageAsset);
                this.parent.addChild(newNode);
            })


        });
    }
    random(n: number, m: number) {
        return Math.random() * (m - n) + n;
    }
    //清空节点数据
    clear() {
        this.parent.destroyAllChildren();
        this.limit = 30;
    }
}